package com.well.rpc.event;

import com.well.rpc.config.ClientDataConfig;
import com.well.rpc.handler.ClientHandler;
import com.well.rpc.model.EventType;
import com.well.rpc.model.TransData;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

/**
 * <p>
 * 处理异常事件
 * </p>
 *
 * @author weedo
 * @since 2022/8/11
 */
@Slf4j
public class ExceptionEvent implements AppEvent {

    /* 如果为true, 表示服务端主动断连 */
    boolean isActive = false;

    @Override
    @PostConstruct
    public void addEvent() {
        EventContext.setEvent(EventType.EXCEPTION, this);
    }

    @Override
    public void doEvent(ChannelHandlerContext channelHandlerContext, TransData transData) {
        log.error(transData.getJsonData());
        isActive = true;
    }

    /**
     * 处理通道异常事件
     */
    public void doChannelInactive() {
        ClientHandler.setChannelContext(null);
        ClientDataConfig.setClientRegisterStatus(false);
        if (isActive) {
            ClientDataConfig.clearRegisterModels();
            return;
        }
        log.info("Will Connect To Server Pool.");
//        ClientHandler.connectServer(socketAddress);
    }

    @Override
    public EventType eventType() {
        return EventType.EXCEPTION;
    }
}
